/**
 * 
 */
package com.snl.component.mail;

import java.io.File;
import java.util.Map;
//import java.util.Properties;
//
//import javax.mail.Authenticator;
//import javax.mail.PasswordAuthentication;
//import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.snl.util.SysPropertiesUtil;

/**
 * @author bryan.liu
 * @date May 13, 2009 
 */
public class EmailEngine {
	
	protected static final Logger logger = Logger.getLogger(EmailEngine.class);
    private JavaMailSenderImpl javaMailSender;
    private VelocityEngine velocityEngine;

    //================================ Setter  ===================================
    public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

    //================================ MimeMail  =====================================
    @SuppressWarnings("unchecked")
	public boolean sendMessage(String from,
                               String to,
                               String subject,
                               boolean isHtml,
                               File[] attachmentFiles,
                               String velocityTemplateLocation,
                               Map model) {
        String textMsg;
        try {
            textMsg = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityTemplateLocation, model);
        } catch (VelocityException e) {
            logger.error("Mail Template Error :\n" + e);
            return false;
        }

        return sendMessage(from, to, subject, isHtml, attachmentFiles, textMsg);
    }

     @SuppressWarnings("unchecked")
	public boolean sendMessage(String from,
                               String to[],
                               String subject,
                               boolean isHtml,
                               File[] attachmentFiles,
                               String velocityTemplateLocation,
                               Map model) {
        String textMsg;
        try {
            textMsg = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityTemplateLocation, model);
        } catch (VelocityException e) {
            logger.error("Mail Template Error :\n" + e);
            return false;
        }

        return sendMessage(from, to, subject, isHtml, attachmentFiles, textMsg);
    }

     /*private class SMTPAuthenticator extends javax.mail.Authenticator
     {
         public PasswordAuthentication getPasswordAuthentication()
         {
             return new PasswordAuthentication("ljh552@gmail.com", "ljh552@sz");
         }
     }*/

     
    public boolean sendMessage(String from,
                               String to,
                               String subject,
                               boolean isHtml,
                               File[] attachmentFiles,
                               String bodyText) {
        try {
        	//This is test code for authenticator
        	/*Properties props = new Properties();
        	props.put("mail.smtp.starttls.enable","true"); 
        	SecurityManager security = System.getSecurityManager();
        	Authenticator auth = new SMTPAuthenticator();

        	Session session = Session.getInstance(props, auth);
        	
        	javaMailSender.setSession(session);*/
        	
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, SysPropertiesUtil.getProperty("mail.msg.encoding"));
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(bodyText, isHtml);
            if (attachmentFiles != null) {
                for (File attFile : attachmentFiles) {
                    if (attFile != null && attFile.exists()) {
                    	
                        helper.addAttachment(attFile.getName(), attFile);
                    }
                }
            }
            javaMailSender.send(message);
            logger.info("Sending mail to [" + to +"]");
        } catch (Exception e) {
            logger.error("Mime Message Error :\n" + e);
            return false;
        }

        return true;
    }

    public boolean sendMessage(String from,
                               String to[],
                               String subject,
                               boolean isHtml,
                               File[] attachmentFiles,
                               String bodyText) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, SysPropertiesUtil.getProperty("mail.msg.encoding"));
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(bodyText, isHtml);
            if (attachmentFiles != null) {
                for (File attFile : attachmentFiles) {
                    if (attFile != null && attFile.exists()) {
                        helper.addAttachment(attFile.getName(), attFile);
                    }
                }
            }
            javaMailSender.send(message);
            logger.info("Sending mail to [" + to +"]");
        } catch (Exception e) {
            logger.error("Mime Message Error :\n" + e);
            return false;
        }

        return true;
    }

    public boolean sendMessage(String to,
    		String subject,
    		boolean isHtml,
    		File[] attachmentFiles,
    		String bodyText){
    	
    	return sendMessage(SysPropertiesUtil.getProperty("mail.msg.from"), to, subject, isHtml, attachmentFiles, bodyText);

    }

}
